using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Comteck.Dto.Orders;
using Comteck.Entities.Orders;
using Comteck.Ktt.Services.Infrastructure;
using ExpressMapper.Extensions;

namespace Comteck.Ktt.Services.Orders {
  /// <summary>
  /// 
  /// </summary>
  public class SelfOrgTagService : BaseKttService, ISelfOrgTagService {
    private readonly IKttRepository<SelfOrgTag, int> _SelfOrgTagRepository;
    private readonly Lazy<ISelfOrgService> selfOrgService;

    public SelfOrgTagService(IKttUnitOfWork unitOfWork,
      Lazy<ISelfOrgService> selfOrgService) : base(unitOfWork) {
      _SelfOrgTagRepository = _unitOfWork.GetRepository<SelfOrgTag, int>();
      this.selfOrgService = selfOrgService;
    }

    /// <summary>
    /// 查询分页主表数据
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<IEnumerable<SelfOrgTagDto>> GetAllAsync() {
      var list = await _SelfOrgTagRepository.GetAllAsync();
      return list.OrderBy(x => x.SeqNo).ThenBy(x => x.Id).MapTo<IEnumerable<SelfOrgTagDto>>();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<SelfOrgTagDto> GetEditModelAsync(int id) {
      SelfOrgTagDto model;
      if (id <= 0) {
        model = new SelfOrgTagDto();
      } else {
        var entity = await _SelfOrgTagRepository.GetByIdAsync(id);
        model = entity.MapTo<SelfOrgTagDto>();
      }

      return model;
    }

    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<AjaxResponse<SelfOrgTagDto>> SaveAsync(SelfOrgTagDto model) {
      var result = new AjaxResponse<SelfOrgTagDto>() {
        Code = 0
      };

      try {
        // check
        await this.CheckSaveAsync(model);

        var dbEntity = await _SelfOrgTagRepository.GetByIdAsync(model.Id);

        if (dbEntity == null) {
          // add
          dbEntity = model.MapTo<SelfOrgTag>();
          dbEntity.CreateTime = DateTime.Now;
          await _SelfOrgTagRepository.AddAsync(dbEntity);
        } else {
          // modify
          model.MapTo(dbEntity);
          await _SelfOrgTagRepository.UpdateAsync(dbEntity);
        }

        result.Code = 1;
        result.Data = dbEntity.MapTo<SelfOrgTagDto>();
      } catch (Exception ex) {
        result.Message = ex.Message;
      }

      return result;
    }

    /// <summary>
    /// 校验合法性
    /// </summary>
    /// <param name="model"></param>
    private async Task CheckSaveAsync(SelfOrgTagDto model) {
      if (model.Name.IsNullOrEmpty()) {
        throw new ComteckException("名称不能为空");
      }

      // 一个用户可以多个分公司，一个分公司只能一个用户
      if (await _SelfOrgTagRepository.CountAsync(x => x.Id != model.Id && x.Name == model.Name) > 0) {
        throw new ComteckException($"名称 {model.Name} 已存在");
      }
    }

    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<AjaxResponse> DeleteAsync(int id) {
      var result = new AjaxResponse() {
        Code = 0,
      };

      var entity = await _SelfOrgTagRepository.GetByIdAsync(id);
      if (entity == null) {
        result.Message = "自提点标签不存在";
        return result;
      }

      if (await selfOrgService.Value.IsTagUsedAsync(id)) {
        result.Message = "自提点标签已经被使用";
        return result;
      }

      // delete
      await _SelfOrgTagRepository.RemoveAsync(entity);
      result.Code = 1;
      return result;
    }

    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="list"></param>
    /// <returns></returns>
    public async Task DeleteBatchAsync(List<int> ids) {
      var list = await _SelfOrgTagRepository.FindAsync(x => ids.Contains(x.Id));
      await _SelfOrgTagRepository.RemoveRangeAsync(list);
    }
  }
}
